import React from 'react';
import { Button, Drawer, Form, Icon, Input, Tooltip, Radio, Select, message, Spin } from 'antd';
import HotRelatedModal from '../hotSpots/hotRelatedModal';
import styles from '../hotSpots/hotQuestion.css';
import { bottomLabelAdd, bottomLabelDetail, bottomLabelEdit, getBottomList } from '@/services/bottomLabel';
import { quickEntryAdd } from '@/services/quickEntry';
import RelatedKnowledgeV2 from '@/utils/RelatedKnowledgeV2';

class EditBottomModal extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      visible: false,
      userTypeChecks: ['all'],
      questions: [],
      bottomArr: [],
      detail: null,
      loading: true
    }
  }

  componentDidMount() {
    if (this.props.onRef) {
      this.props.onRef(this)
    }
  }

  /* 打开抽屉 */
  openInit = row => {
    this.setState({ visible: true, detail: row, loading: row ? true : false }, () => {
      this.getAllBottomList(row)
    })
  }

  /* 获取底部标签详情 */
  getBottomLabelDetail = async () => {
    const { detail } = this.state;
    const res = await bottomLabelDetail({ id: detail.id })
    const userTypeList = res.userTypeList ? res.userTypeList.map(item => item.userTypeId) : [];
    if (userTypeList.length === 0) {
      userTypeList.push('all');
    };
    this.props.form.setFieldsValue({
      labelName: res.labelName,
      defaultLabel: res.defaultLabel ? '1' : '0',
      relLabelIdList: res.relLabelList.map(item => item.labelId),
      userType: userTypeList,
    });
    let questions = res?.relQaList && res.relQaList.length > 0 ? res.relQaList.map(item => ({
      id: item.qaId,
      basicQuestion: item.question,
      type: item.qaType
    })) : [];
    this.setState({ userTypeChecks: userTypeList, questions, loading: false })
  }

  /* 获取当前已添加的所有底部标签 */
  getAllBottomList = async (row) => {
    const { applicationId } = this.props
    const res = await getBottomList({ current: 1, size: 999999, applicationId, labelName: '', userTypeId: '' })
    this.setState({ bottomArr: res.records }, () => {
      if (row) {
        this.getBottomLabelDetail();
      }
    })
  }

  /* 关闭抽屉 */
  cancelBottomModal = () => {
    this.props.form.resetFields()
    this.setState({
      visible: false,
      userTypeChecks: ['all'],
      questions: []
    })
  }

  /* 选择用户类型 */
  changeUserType = value => {
    let { userTypeChecks } = this.state;
    //选择了其他的用户类型 又选择了全部类型 则需要删掉其他的用户类型 只保留全部类型
    if (value === 'all') {
      this.props.form.setFieldsValue({ userType: ['all'] });
      userTypeChecks = ['all'];
    } else {
      userTypeChecks.push(value);
    }
    this.setState({ userTypeChecks });
  };

  /* 去掉用户类型的选择 */
  deselectUserType = value => {
    if (value === 'all') {
      this.setState({ userTypeChecks: [] });
    }
  };

  /* 打开关联知识点 */
  openRelatedModal = () => {
    const { questions } = this.state;
    this.RelatedKnowledge.openAndInit(questions)
  }

  /* 选择关联知识点后 */
  addQuestionByBottom = (questions) => {
    this.setState({ questions })
  }

  /** 取消关联 */
  removeRelatedQus = (question) => {
    let { questions } = this.state;
    questions = questions.filter(item => item != question);
    this.setState({ questions })
  }

  /* 保存/编辑标签基础信息前校验 */
  doFinished = e => {
		e.stopPropagation();
    e.preventDefault();
    const that = this;
    const { questions } = that.state;
    const { applicationId } = that.props;
    that.props.form.validateFields((errors, values) => {
      if (!errors) {
        const hotQuestionList = [];
        for (const item of questions) {
          if(item.type == -1){
            hotQuestionList.push({ qaId: item.id, qaType: item.type,question:item.basicQuestion });
          }else{
            hotQuestionList.push({ qaId: item.id, qaType: item.type });
          }
        };
        let relQas = [...hotQuestionList];
        if (!(relQas.length>0)) {
          message.error('请选择对应知识点')
          return false
        };
        const userTypeIdList = values.userType ? values.userType : [];
        let obj = {
          labelName: values.labelName,
          applicationId,
          userTypeIdList: userTypeIdList.indexOf('all') > -1 ? [] : userTypeIdList,
          relQas,
          defaultLabel: values.defaultLabel == 1,
          relLabelIdList: values.relLabelIdList ? values.relLabelIdList : []
        };
        that.doSubmitFetch(obj);
      }
    });
  }

  /* 编辑/保存-请求 */
  doSubmitFetch = async obj => {
    const that = this;
    const { detail } = that.state;
    let res = {};
    if (detail) {
      /* 编辑 */
      obj.id = detail.id;
      res = await bottomLabelEdit(obj)
    } else {
      /* 保存 */
      res = await bottomLabelAdd(obj);
    }
    message.info(res.msg)
    that.cancelBottomModal();
    that.props.refreshTableList();
  }

  addSelfQuestion = () => {
    const { questions } = this.state;
    questions.push({
      id:"",
      basicQuestion:"",
      type:-1,
      qaType:-1
    })
    this.setState({questions})
  }

  doChangeQuestion = (e,index) => {
    const { questions } = this.state;
    let newQuestions = []
    for(let i in questions){
      if(questions[i].type == -1 && i == index){
        questions[i].basicQuestion = e.target.value
      }

      newQuestions.push(questions[i])
    }

    this.setState({
      questions:newQuestions
    })
  }

  render() {
    const { visible, userTypeChecks, questions, bottomArr, loading, detail } = this.state;
    const { userList, applicationId } = this.props;
    const { getFieldDecorator } = this.props.form
    const formItemLayout = {
      labelCol: {
        xs: { span: 24 },
        sm: { span: 5 },
      },
      wrapperCol: {
        xs: { span: 24 },
        sm: { span: 19 },
      },
    };
    const renderType = type => {
      let txt = ''
      switch (type) {
        case -1:
          txt = '自定义';
          break;
        case 1:
          txt = '问答';
          break;
        case 2:
          txt = '导图';
          break;
        case 3:
          txt = '多轮';
          break;
        case 4:
          txt = '表单';
          break;
      }
      return txt
    }
    const renderLabel = (label, tip) => {
      return (
        <label>
          {label}
          <Tooltip placement="topLeft" title={tip}>
            <Icon type="question-circle" style={{ verticalAlign: 'baseline', margin: '0 5px' }} />
          </Tooltip>
        </label>
      )
    }
    return (
      <Drawer
        title={'标签添加/编辑'}
        visible={visible}
        width={650}
        onClose={this.cancelBottomModal}
      >
        <Spin spinning={loading}>
          <Form {...formItemLayout}>
            <Form.Item label={'标签名称'}>
              {
                getFieldDecorator('labelName', { rules: [{ required: true, message: '请填写标签名称' }] })(
                  <Input maxLength={6} />
                )
              }
            </Form.Item>
            <Form.Item label={renderLabel('对应知识点', '用户点击该标签后将触发该知识点')}>
              <Button icon={'plus'} style={{ marginRight: 16 }} onClick={this.openRelatedModal}>添加</Button>
              <Button onClick={this.addSelfQuestion}>添加自定义</Button>
            </Form.Item>
            {questions && questions.length > 0 && (
              questions.map((questionItem, index) => (
                <div className={styles.hotBox} style={{ marginBottom: 16, marginTop: index == 0 ? -12 : 0, justifyContent: 'center' }} key={index}>
                  <div className={styles.hotPrefix} style={{ lineHeight: '20px' }}>{renderType(questionItem.type)}</div>
                  {/* <div className={styles.hotItem} style={{ marginRight: 10, lineHeight: '25px', padding: '7px 10px' }}>{questionItem.basicQuestion}</div> */}
                  {
                    questionItem.type == -1 ? (
                      <Input className={styles.hotItem} style={{minHeight:'40px',lineHeight:'40px',border:"none"}} value={questionItem.basicQuestion} onChange={e => this.doChangeQuestion(e,index)} />
                    ) : (
                      <div className={styles.hotItem} style={{ marginRight: 10, lineHeight: '25px', padding: '7px 10px' }}>
                        {questionItem.basicQuestion}
                      </div>
                    )
                  }
                  {/* <Button icon={'plus'} onClick={this.openRelatedModal}>更换</Button> */}
                  <Icon
                    type='close-circle'
                    style={{ margin: "0px 10px", fontSize: "20px", verticalAlign: 'middle' }}
                    onClick={() => this.removeRelatedQus(questionItem)}
                  />
                </div>
              ))
            )}
            <Form.Item label={renderLabel('是否默认标签', '默认标签将在会话发起后默认显示')}>
              {getFieldDecorator('defaultLabel', { initialValue: '1' })(
                <Radio.Group>
                  <Radio value="1">是</Radio>
                  <Radio value="0">否</Radio>
                </Radio.Group>
              )}
            </Form.Item>
            <Form.Item label={renderLabel('相关标签', '用户点击当前标签后，输入框上方更新显示其相关标签，若没有相关标签则仍然保持原标签显示')}>
              {
                getFieldDecorator('relLabelIdList')(
                  <Select mode="multiple">
                    {
                      bottomArr.map((item, index) => {
                        return <Select.Option value={item.id} key={item.id} disabled={detail && detail.id === item.id}>{item.labelName}</Select.Option>
                      })
                    }
                  </Select>
                )
              }
            </Form.Item>
            <Form.Item label={renderLabel('适用用户类型', '选择设置哪种类型的用户可以看到该标签')}>
              {getFieldDecorator('userType', { initialValue: ['all'], rules: [{ required: true, message: '请选择用户类型' }] })(
                <Select
                  mode="multiple"
                  onSelect={this.changeUserType}
                  onDeselect={this.deselectUserType}
                >
                  <Select.Option value={'all'}>默认类型</Select.Option>
                  {userList.map((item, index) => {
                    return (
                      <Select.Option
                        disabled={userTypeChecks.indexOf('all') != -1}
                        value={item.id}
                        key={item.id}
                      >
                        {item.tagName}
                      </Select.Option>
                    );
                  })}
                </Select>
              )}
            </Form.Item>
          </Form>
        </Spin>

        <div
          style={{
            position: 'absolute',
            right: 0,
            bottom: 0,
            width: '100%',
            borderTop: '1px solid #e9e9e9',
            padding: '10px 16px',
            background: '#fff',
            textAlign: 'right',
          }}
        >
          <Button onClick={this.cancelBottomModal} style={{ marginRight: 8 }}>取消</Button>
          <Button onClick={this.doFinished} type="primary">确定</Button>
        </div>

        <RelatedKnowledgeV2 
          onRef={ref => this.RelatedKnowledge = ref}
          applicationId={applicationId}
          // chooseType='radio'
          chooseType=''
          getRelatedList={this.addQuestionByBottom}
        />
      </Drawer>
    );
  }
}

export default Form.create()(EditBottomModal)
